package com.cxyzy.feedbackdemo

import android.app.Activity
import android.content.Context

import java.lang.ref.WeakReference

object ShakeManager {
    private var isShakeListenerOn = false
    private var dialog: FeedbackDialog? = null
    private var mActivity: WeakReference<Activity>? = null

    fun initSensor(context: Context) {
        val sensorHelper = SensorManagerHelper(context)
        sensorHelper.onShakeListener = this::onShake
    }

    fun start(activity: Activity) {
        mActivity = WeakReference(activity)
        isShakeListenerOn = true
    }

    fun stop() {
        isShakeListenerOn = false
    }

    @Synchronized
    private fun onShake() {
        val activity = mActivity!!.get()
        if (isShakeListenerOn && activity != null) {
            closeDialogWhenActivityChanges()
            if (dialog == null || hasActivityChanged()) {
                dialog = FeedbackDialog(activity)
            }
            if (!dialog!!.isShowing && !activity.isFinishing) {
                dialog!!.show()
            }
        }
    }

    /**
     * 因为dialog是绑定到activity的，如果activity变化了，就关闭之前的dialog，后面摇晃手机再次生成dialog。
     */
    private fun closeDialogWhenActivityChanges() {
        if (dialog == null || dialog!!.activity == null || dialog!!.activity.isFinishing || dialog!!.activity.isDestroyed) {
            return
        }
        if (dialog != null && hasActivityChanged()) {
            dialog!!.dismiss()
        }
    }

    private fun hasActivityChanged(): Boolean {
        var result = false
        val activity = mActivity!!.get()
        if (activity != null && activity != dialog!!.activity) {
            result = true
        }
        return result
    }
}
